package com.example.graduatetest.view.model;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.appcompat.widget.Toolbar;
import androidx.lifecycle.ViewModel;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.example.graduatetest.R;
import com.example.graduatetest.activitys.AskLeaveActivity;
import com.example.graduatetest.activitys.FindCardActivity;
import com.example.graduatetest.activitys.HomeActivity;
import com.example.graduatetest.activitys.NoticeListActivity;
import com.example.graduatetest.activitys.NoticeWriteActivity;
import com.example.graduatetest.activitys.ScoreAllActivity;
import com.example.graduatetest.activitys.ScorePersonActivity;
import com.example.graduatetest.activitys.SendCardActivity;
import com.example.graduatetest.activitys.TeacherPersonActivity;
import com.example.graduatetest.activitys.UploadScoreActivity;
import com.example.graduatetest.adapter.ActionItemAdapter;
import com.example.graduatetest.adapter.StudentItemAdapter;
import com.example.graduatetest.bean.Classes;
import com.example.graduatetest.bean.Icon;
import com.example.graduatetest.bean.Student;
import com.example.graduatetest.bean.User;
import com.example.graduatetest.callback.StudentList;
import com.example.graduatetest.databinding.ActivityAskLeaveBinding;
import com.example.graduatetest.databinding.ActivityClassDetailBinding;
import com.example.graduatetest.model.ClassModel;
import com.example.graduatetest.utils.Constant;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ClassDetailViewModel extends ViewModel {

    private Activity activity;
    private ActivityClassDetailBinding binding;
    private BaseAdapter mAdapter = null;
    //grid网格数据
    private List<Icon> mData = new ArrayList<>();
    private List<Student> studentList = new ArrayList<>();
    private Handler handler = new Handler();
    //定义课程实体
    private Classes ownClass;
    private User user;
    //定义返回值，判断图片的来源
    private int Photo_ALBUM = 1, CAMERA = 2;
    //定义图片的路径
    private String imagePath = null;
    //定义图片的uri
    private Uri imageUri;


    public void init(Activity activity, ActivityClassDetailBinding binding,Classes ownClass){
        this.activity = activity;
        this.binding = binding;
        this.ownClass = ownClass;
        user = Constant.checkStudentOrTeacher(activity);
        initView();
        toolbarInit();
        initGridView();
        getData();
    }

    //初始toolbar
    private void toolbarInit(){
        Toolbar toolbar = binding.toolbar4;
        toolbar.setTitle(ownClass.getName());
        toolbar.setNavigationIcon(R.drawable.ic_arrow_back_black_24dp);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                activity.onBackPressed();
            }
        });

        //判断
        SharedPreferences.Editor editor = activity.getApplication().getSharedPreferences("data", Context.MODE_PRIVATE).edit();
        editor.putBoolean("isLeave", false);
        editor.apply();

    }

    //获取数据
    private void getData(){
        ClassModel.getStudentList(ownClass.getId(), new StudentList() {
            @Override
            public void onSuccess(List<Student> list) {
                studentList = list;
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        initRecyclerView();
                    }
                });
                Log.e("haha","获取学生列表成功+"+studentList.size());
            }

            @Override
            public void onFailed() {
                studentList = null;
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        binding.tvNoStudent.setVisibility(View.VISIBLE);
                    }
                });
                Log.e("haha","获取学生列表失败");
            }
        });
    }

    //初始化RecyclerView
    private void initRecyclerView(){
        binding.recyclerView.setVisibility(View.VISIBLE);
        LinearLayoutManager layoutManager = new LinearLayoutManager(activity);
        binding.recyclerView.setLayoutManager(layoutManager);
        if(studentList != null){
            StudentItemAdapter studentItemAdapter = new StudentItemAdapter(studentList);
            binding.recyclerView.setAdapter(studentItemAdapter);
        }
    }
    //初始化课程，同学
    private void initView(){
        binding.tvClassId.setText("课程号："+ownClass.getId());
        binding.tvClassNumber.setText("选课人数:"+ownClass.getNumber());
    }

    //初始化网格布局
    private void initGridView(){

        mData.add(new Icon(R.drawable.notice, "通知"));//0
        mData.add(new Icon(R.drawable.data, "作业"));//1
        mData.add(new Icon(R.drawable.card, "打卡"));//2
        mData.add(new Icon(R.drawable.count, "成绩统计"));//3
        mData.add(new Icon(R.drawable.homework, "成绩查询"));//4
        mData.add(new Icon(R.drawable.score, "成绩上传"));//5
        mData.add(new Icon(R.drawable.person_male, "老师简介"));//6
        mData.add(new Icon(R.drawable.class_info, "考勤"));//7
        mData.add(new Icon(R.drawable.ask_class_student, "请假"));//8
        mData.add(new Icon(R.drawable.ask_class_teacher, "批假"));//9
        mData.add(new Icon(R.drawable.face,"录入人脸"));//10




        mAdapter = new ActionItemAdapter(activity.getApplicationContext(), mData);
        binding.gdAction.setAdapter(mAdapter);

        binding.gdAction.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent;
                switch (position){
                    case 0:
                        if(!user.isStudent()){
                            intent = new Intent(activity, NoticeWriteActivity.class);
                        }else{
                            intent = new Intent(activity, NoticeListActivity.class);
                        }
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.putExtra("classes", ownClass);
                        intent.putExtra("type", "公告");
                        activity.startActivity(intent);

                        break;
                    case 1:
                        if(!user.isStudent()){
                            intent = new Intent(activity, NoticeWriteActivity.class);
                        }else{
                            intent = new Intent(activity, NoticeListActivity.class);
                        }
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.putExtra("classes", ownClass);
                        intent.putExtra("type", "作业");
                        activity.startActivity(intent);
                        break;
                    case 2:
                        if(user.isStudent()){
                            intent = new Intent(activity, FindCardActivity.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            intent.putExtra("class_number", ownClass.getId());
                            activity.startActivity(intent);
                        }else{
                            Toast.makeText(activity, "你没有权限",Toast.LENGTH_SHORT).show();
                        }

                        break;
                    case 3:
                        intent = new Intent(activity, ScoreAllActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.putExtra("classes", ownClass);
                        activity.startActivity(intent);
                        break;
                    case 4:
                        if (user.isStudent()){
                            intent = new Intent(activity, ScorePersonActivity.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            intent.putExtra("classes", ownClass);
                            activity.startActivity(intent);
                        }else{
                            Toast.makeText(activity, "你没有权限",Toast.LENGTH_SHORT).show();
                        }
                        break;
                    case 5:
                        if(!user.isStudent()){
                            intent = new Intent(activity, UploadScoreActivity.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            intent.putExtra("class_name", ownClass.getName());
                            intent.putExtra("class_number_send", ownClass.getId());
                            activity.startActivity(intent);
                        }else{
                            Toast.makeText(activity, "你没有权限",Toast.LENGTH_SHORT).show();
                        }
                        break;
                    case 6:
                        intent = new Intent(activity, TeacherPersonActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.putExtra("teacher_id", ownClass.getTeacher_number());
                        activity.startActivity(intent);
                        break;
                    case 7:
                        if(!user.isStudent()){
                            intent = new Intent(activity, SendCardActivity.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            intent.putExtra("classes", ownClass);
                            activity.startActivity(intent);
                        }else{
                            Toast.makeText(activity, "你没有权限",Toast.LENGTH_SHORT).show();
                        }
                        break;
                    case 8:
                        if(user.isStudent()){
                            intent = new Intent(activity, AskLeaveActivity.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            intent.putExtra("class_number", ownClass.getId());
                            activity.startActivity(intent);
                        }else{
                            Toast.makeText(activity, "你没有权限",Toast.LENGTH_SHORT).show();
                        }
                        break;
                    case 9:
                        if(!user.isStudent()){
                            SharedPreferences.Editor editor = activity.getApplication().getSharedPreferences("data", Context.MODE_PRIVATE).edit();
                            editor.putBoolean("isLeave", true);
                            editor.apply();
                            intent = new Intent(activity, NoticeListActivity.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            intent.putExtra("classes", ownClass);
                            intent.putExtra("type", "请假");
                            activity.startActivity(intent);
                        }else{
                            Toast.makeText(activity, "你没有权限",Toast.LENGTH_SHORT).show();
                        }
                        break;
                    case 10:
                        if(user.isStudent()){
                           showDialog();
                        }else{
                            Toast.makeText(activity, "教师无需录入人脸信息",Toast.LENGTH_SHORT).show();
                        }
                    default:
                        break;

                }
            }
        });

    }

    //显示Dialog录入信息
    private void showDialog(){
        new AlertDialog.Builder(activity)
                .setTitle("系统提示")
                // 设置显示的内容
                .setMessage("请选择上传方式")
                //右边按钮
                .setPositiveButton("返回",
                        new DialogInterface.OnClickListener() {// 添加确定按钮
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // 确定按钮的响应事件，取消上传
                            }
                        }
                )
                //中间按钮
                .setNeutralButton("从相册上传", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        //选择数据
                        Intent in = new Intent(Intent.ACTION_PICK);
                        //选择的数据为图片
                        in.setType("image/*");
                        activity.startActivityForResult(in, Photo_ALBUM);
                    }
                })
                //左边按钮
                .setNegativeButton("拍照",
                        new DialogInterface.OnClickListener() {

                            @TargetApi(Build.VERSION_CODES.M)
                            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
                            @Override
                            public void onClick(
                                    DialogInterface dialog,
                                    int which) {

                                //7.0拍照必加
                                StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
                                StrictMode.setVmPolicy(builder.build());
                                builder.detectFileUriExposure();

                                //临时照片存储地址
                                File outputImage = new File(Environment.getExternalStorageDirectory()
                                        + File.separator + "face.jpg");
                                try {
                                    if (outputImage.exists()) {
                                        outputImage.delete();
                                    }
                                    //创建零时地址
                                    outputImage.createNewFile();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }

                                //获取Uri
                                imageUri = Uri.fromFile(outputImage);   //将file转成uri对象
                                imagePath = outputImage.getAbsolutePath();

                                //，是传递你要保存的图片的路径，系统会根据你提供的地址进行保存图片
                                Log.i("拍照图片路径", imagePath);

                                //跳转相机
                                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                                //相片输出路径
                                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);

                                //返回照片路径
                                activity.startActivityForResult(intent, CAMERA);
                            }
                        })
                .show();// 在按键响应事件中显示此对话框
    }

    public String getImagePath(){
        return imagePath;
    }


}
